<template>
  <div class="inlibrary">
    <my-head title="入库管理" :isRightClick = "true"/>
    
    <mu-text-field v-show="isShowVin" v-model="vin" placeholder="VIN" ref="vin" class='input' @keyup.enter.native="getVin()"><i class="iconfont icon-saomiao" @click="scan('showVin')"></i></mu-text-field>
    
    <mu-text-field v-show="isSureVin" v-model="surevin" placeholder="VIN" ref="surevin" class='input' @keyup.enter.native="driverAction(2)"><i class="iconfont icon-saomiao" @click="scan('sureVin')"></i></mu-text-field>

    <mu-paper class="paper" :z-depth="2" v-show="isShowCard" >
        <div class="list-content">VIN ：<span>{{vin}}</span></div>
        <div class="list-content">车型：<span>{{infoForm.carCode}}</span><em class="space"></em>颜色：<span>{{infoForm.color}}</span></div>
        <div class="list-content">类型：<span>{{infoForm.type}}</span></div>
        <div class="list-content">库位：<span class="library-position">{{infoForm.location}}</span></div>
    </mu-paper>

    <div class="btn">
        <mu-button large v-if="refuseBtn" color="primary" @click="openBottomSheet()">拒绝任务</mu-button>
        <mu-button large v-if="abnormal" color="primary" @click="goAbnormal">异常上报</mu-button>
        <mu-button large v-if="receiveBtn" color="primary" @click="driverAction(1)">领取任务</mu-button>
        <mu-button large v-if="pickCarBtn" color="primary" @click="driverAction(2)">取车确认</mu-button>
        <mu-button large v-if="doneBtn" color="primary" @click="isDoneUpdate">确认完成</mu-button>
    </div>

    <mu-bottom-sheet :open.sync="openRefuseReasons">
        <mu-list @item-click="closeBottomSheet">
            <mu-sub-header>请拒绝原因</mu-sub-header>
            <mu-list-item button v-for="(item,index) in refuseReasons" :key="index" @click="driverAction(0, item.reason)">
                <mu-list-item-title>{{item.reason}}</mu-list-item-title>
            </mu-list-item>
        </mu-list>
    </mu-bottom-sheet>
    <mu-dialog title="是否确认完成?" width="600" max-width="80%" :esc-press-close="false" :overlay-close="false" :open.sync="isuredoneDialog">
        <mu-button slot="actions" flat color="primary" @click="sureDone()">是</mu-button>
        <mu-button slot="actions" flat color="primary" @click="closeThisConfirm">否</mu-button>
    </mu-dialog>
    <div class="targetLocation" ref="test" @click="watchTest">
        当前库位坐标
        <div>经：{{longitude}}</div>
        <div>纬：{{latitude}}</div>
        <div>半径：{{railRadius}}</div>
        <div>距离：{{lengths}}</div>
    </div>
    <scanning v-if="isScanning" :mark="scanMark" v-on:childByValue="childByValue" v-on:closeing="closeing"/>
  </div>
</template>

<script>
import myHead from '@/components/header'
import scanning from "@/components/scanning"
import api from "@/common/api"
export default {
  name: 'inlibrary',
  components: {
    myHead, scanning
  },
  data () {
    return {
        scanMark: '',
        isScanning: false,
        iswatchTest: false,
        isuredoneDialog: false,
        vin: "",
        surevin: '',
        openRefuseReasons: false,
        refuseReasons: [],
        isSureVin: false,
        isShowVin: false,
        isShowCard: false,
        refuseBtn: false,
        receiveBtn: false,
        pickCarBtn: false,
        doneBtn: false,
        infoForm: {
            carCode: "",
            color: "",
            type: "",
            location: ""
        },
        abnormal: false,
        latitude: 0,
        longitude: 0,
        railRadius: 10,
        lengths: 0,
        requestOnce: true,
        isDisCompute: true,
        isAutoDone: true // 是否自动完成
    }
  },
  methods: {
    closeing (val) {
      val ? this.isScanning = false : null;
    },
    childByValue (val) {
      if(val){
        if(val.split('&')[1] == 'showVin'){
          this.vin = val.split('&')[0];
          this.getVin();
        }else if(val.split('&')[1] == 'sureVin'){
          this.surevin = val.split('&')[0];
          this.driverAction(2);
        }
      }
    },
    scan (txt) {
      this.scanMark = txt;
      this.isScanning = true;
    },
    watchTest(){
      if(this.iswatchTest){
        this.$refs.test.classList.remove('hover')
      }else{
        this.$refs.test.classList.add('hover')
      }
      this.iswatchTest = !this.iswatchTest;
    },
    /* 异常跳转 */
    goAbnormal () {
      this.$router.push({name: "abnormal", params: {vin: this.vin}});
    },
    /*手动确认完成 */
    isDoneUpdate () {
        this.disCompute("MANUAL", ()=>{
            // 在电子围栏半径内
            this.isuredoneDialog = true;
        });
    },
    sureDone(){
        this.doneUpdate('MANUAL');
        this.isuredoneDialog = false;
    },
    closeThisConfirm(){
        this.isuredoneDialog = false;
    },
    /*确认完成 */
    doneUpdate (manual) {
        if(this.isAutoDone){
            this.isAutoDone = false;
            let data = Object.assign({},this.$store.state.user,{
                content: {
                    vin : this.vin,
                    action: manual
                }
            });
            /* 发送post请求 */
            this.common.reqData(api.app('inlibraryConfirm'), data, res=>{
                this.isAutoDone = true;
                console.log('res.data5',res.data);
                if(res.data.status == 100){
                    this.Toast.success({
                        duration: 1500,
                        mask: true,
                        message: "入库成功"
                    });
                    this.abnormal = this.doneBtn = false;
                    manual == "RAIL" ? this.common.tts("任务已自动完成") : 0;
                    this.longitude = this.latitude = 0;
                    this.isDisCompute = false;
                }else{
                    this.Toast({
                        mask: true,
                        message: res.data.msg
                    });
                }
            },err =>{
                this.isAutoDone = true;
                console.log(err)
            });
        }else{
            return false;
        }
    },
    closeBottomSheet () {
        this.openRefuseReasons = false;
    },
    openBottomSheet () {
        this.openRefuseReasons = true;
    },
    /*领取 和 取车确认 拒绝任务 */
    driverAction (flag, reason) {
        let data = null;
        if(this.surevin == ''){
            data = Object.assign({},this.$store.state.user,{
                content: {
                    vin: this.vin,
                    flag: flag,
                    issurevin: false
                }
            });
        }else{
            data = Object.assign({},this.$store.state.user,{
                content: {
                    vin: this.surevin,
                    flag: flag,
                    issurevin: true
                }
            });
        }
        if(flag === 0){
            // 如果是拒绝，那么请选择拒绝原因
            data = Object.assign({},this.$store.state.user,{
                content: {
                    vin: this.vin,
                    flag: flag,
                    issurevin: false,
                    reason: reason
                }
            });
        }
        if(this.requestOnce){
            this.requestOnce = false;
            /* 发送post请求 */
            this.common.reqData(api.app('inlibraryUpdate'), data, res=>{
                console.log('res.data4',res.data);
                this.requestOnce = true;
                if(res.data.status == 100){
                    if(flag == 0){
                        this.pickCarBtn = false,
                        this.refuseBtn = false,
                        this.receiveBtn = false,
                        this.isShowVin = false;
                        // 提示
                        this.Toast({
                            duration: 1500,
                            mask: true,
                            message: '已拒绝任务'
                        });
                    }else if(flag == 1){
                        this.abnormal = true;
                        this.pickCarBtn = true,
                        this.refuseBtn = false,
                        this.receiveBtn = false,
                        this.isShowVin = false;
                        // 提示
                        this.Toast({
                            duration: 1500,
                            mask: true,
                            message: '已领取任务'
                        });
                    }else{
                        // 提示
                        this.Toast({
                            duration: 1500,
                            mask: true,
                            message: '已取车'
                        });
                        this.refuseBtn = false,
                        this.receiveBtn = false,
                        this.isShowVin = false;
                        this.isSureVin = false;
                        this.pickCarBtn = false,
                        this.doneBtn = true;
                        this.abnormal = true;
                        this.latitude = res.data.content.latitude;
                        this.longitude = res.data.content.longitude;
                        this.railRadius = res.data.content.railRadius;
                        this.infoForm.location = res.data.content.location;
                    }
                }else{
                    this.Toast({
                        mask: true,
                        message: res.data.msg
                    });
                }
            },err =>{
                this.requestOnce = true;
                console.log(err)
            });
        }
    },
    getVin () {
        let data = Object.assign({},this.$store.state.user,{
            content: {
                vin: this.vin
            }
        });
        if(this.requestOnce){
            this.requestOnce = false;
            /* 发送post请求 */
            this.common.reqData(api.app('inlibraryVin'), data, res=>{
                console.log('res.data3',res.data);
                this.requestOnce = true;
                if(res.data.status == 100){
                    this.infoForm = {
                        carCode: res.data.content.vehicleType,
                        color: res.data.content.color,
                        type: res.data.content.type,
                        location: res.data.content.location
                    }
                    this.latitude = res.data.content.latitude;
                    this.longitude = res.data.content.longitude;
                    this.railRadius = res.data.content.railRadius;
                    this.isShowVin = false;
                    this.doneBtn = true, this.abnormal = true, this.isShowCard = true;
                    this.isDisCompute = true;
                }else{
                    this.Toast({
                        mask: true,
                        message: res.data.msg
                    });
                }
            },err =>{
                this.requestOnce = true;
                console.log(err)
            });
        }
    },
    searchTask (data) {
        /* 发送post请求 */
        this.common.reqData(api.app('inlibrary'), data, res=>{
            console.log('res.data1',res.data);
            let resData = res.data.content;
            if(res.data.status == 100){
                if(resData.task == null){
                    this.isShowVin = true;
                    setTimeout(() => {
                        // 获取焦点
                        this.$refs.vin.$el.children[0].getElementsByTagName('input')[0].focus();
                        window.plus ? plus.key.hideSoftKeybord() : 0;
                    }, 50);
                    return ;
                }
                if(resData.task.flag == 0){
                    this.resContent(res);
                    this.isShowCard = true;
                    this.refuseBtn = true, this.receiveBtn = true;
                }else if(resData.task.flag == 1){
                    // 取车确认
                    this.resContent(res);
                    this.isShowCard = true;
                    this.isSureVin = true;
                    this.pickCarBtn = true;
                    this.abnormal = true;
                }else if(resData.task.flag == 2){
                    // 确认完成
                    this.abnormal = true;
                    this.doneBtn = true, this.isShowCard = true;
                    this.resContent(res);
                }
            }else{
                console.log('失败');
            }
        },err =>{
            console.log(err)
        });
    },
    resContent (res) {
        // 获取数据
        this.latitude = res.data.content.task.latitude;
        this.longitude = res.data.content.task.longitude;
        this.railRadius = res.data.content.task.railRadius;
        this.vin = res.data.content.task.vin;
        this.infoForm = {
            carCode: res.data.content.task.vehicleType,
            color: res.data.content.task.color,
            type: res.data.content.task.type,
            location: res.data.content.task.location
        }
    },
    disCompute (manual, func) {
      if(this.isDisCompute){
        console.log('定位或速度已经改变',this.longitude,this.latitude)
        this.common.distanceCompute({
            latitude: this.latitude,
            longitude: this.longitude
        },{
            latitude: this.$store.state.latitude,
            longitude: this.$store.state.longitude
        }, this.railRadius, ()=>{
            this.doneUpdate(manual)
        }, func);
        // 测试用距离计算
        let _this = this;
        let selfPoint = new plus.maps.Point(this.longitude, this.latitude)
        let targetPoint = new plus.maps.Point(this.$store.state.longitude, this.$store.state.latitude)
        plus.maps.Map.calculateDistance(targetPoint, selfPoint, function (event) {
            var distance = event.distance // 转换后的距离值
            _this.lengths = distance
        }, function (e) {
            console.log('Failed:' + JSON.stringify(e))
        })
      }
    }
  },
  mounted () {
    let data = null;
    if(this.$route.params.vin){
      data = Object.assign({},this.$store.state.user,{
        content:{
          vin: this.$route.params.vin
        }
      });
    }else{
      data = this.$store.state.user;
    }
    // 搜索是否有未完成的入库任务
    this.searchTask(data);
    // 拒绝原因
    this.refuseReasons = this.$store.state.refuseReasons;
  },
  computed: {
    latitudeChange () {
        return this.$store.state.latitude;
    },
    longitudeChange () {
        return this.$store.state.longitude;
    },
    speedChange () {
        return this.$store.state.speed;
    }
  },
  watch:{
    latitudeChange: function(data) {
        this.disCompute("RAIL");
    },
    longitudeChange: function(data) {
        this.disCompute("RAIL");
    },
    speedChange: function(data) {
        this.disCompute("RAIL");
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.inlibrary{
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
}
.input{
    display: block;
    margin: 15px auto;
    width: 85%;
}
.paper, .state, .msg{
    width: 85%;
    margin: 4em auto 0;
    padding: 1.5em 0;
}
.state, .msg{
    text-align: center;
    color: red;
    font-size: 1em;
}
.list-content{
    padding: 8px 20px;
}
.library-position{
    font-size: 2.2em;
    font-weight: bold;
    color: red;
    text-shadow: 2px 2px 5px rgba(0,0,0,0.5);
}
.space{
    padding: 0 20px;
}
.btn{
  position: absolute;
  bottom: 20px;
  left: 7.5%;
  right: 7.5%;
  display: flex;
  justify-content: space-around;
}
.btn .mu-raised-button{
  font-size: 18px;
  height: 40px;
  line-height: 40px;
}
</style>
